package com.zhangxin.designmode.fiveprinciple.liskovsubstitutionprinciple.after;

import org.springframework.util.StringUtils;
import sun.net.www.http.HttpClient;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhangxin
 * @date 2022/4/9
 */
public class SecurityTransporter extends Transporter {

    private String appId;
    private String appToken;

    public SecurityTransporter(HttpClient httpClient, String appId, String appToken) {
        super(httpClient);
        this.appId = appId;
        this.appToken = appToken;
    }

    /**
     * 如果传递进 demoFunction() 函数的是父类 Transporter 对象，那
     * demoFunction() 函数并不会有异常抛出，但如果传递给 demoFunction() 函数的是子类
     * SecurityTransporter 对象，那 demoFunction() 有可能会有异常抛出。尽管代码中抛出的
     * 是运行时异常（Runtime Exception），我们可以不在代码中显式地捕获处理，但子类替换
     * 父类传递进 demoFunction 函数之后，整个程序的逻辑行为有了改变
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public HttpServletResponse sendRequest(HttpServletRequest request) throws Exception {
        if (!StringUtils.hasLength(appId) || !StringUtils.hasLength(appToken)) {
            throw new Exception();
        }
        request.setAttribute("app-id", appId);
        request.setAttribute("app-token", appToken);
        return super.sendRequest(request);
    }
}
